<?php
namespace app\api\controller;
use think\facade\Db;
use app\common\controller\Api;
use think\facade\Config;
use think\facade\Session;
use app\common\library\Sms as Smslib;

/*
 * 权益接口
 * @author swq 
 * @date 2020-10-14
*/
class Ordercoupon extends Api
{
    //不需要登录的方法
    protected $noNeedLogin = ['heXiao', 'checkUserIsQuanYi','receiveCoupon','getWxCoupon','getAccessToken'];
    protected $noNeedRight = '*';

    //三方配置
    protected $fromchannelId = 'HB13000002'; //渠道标识
    protected $signMerchantNo = '3178035188579395'; //证书机构号，服务端是根据该字段进行查找证书信息的
    protected $agreeId = '20200903030100040983812988993549'; //协议号
    protected $signType = 'S001'; //验签类型
    protected $certpath = '/cert/世纪恒通科技股份有限公司.P12'; //证书路径 
    protected $priKeyPwd = '53778345'; //证书密码
    // protected $urls = 'https://mapi.test.bestpay.net/gapi'; //测试环境
    protected $urls = 'https://mapi.bestpay.com.cn/gapi'; //生产环境
    protected $biaoshi = '7710123000300238'; //销售品号
    protected $biaoshi1 = '7100010114'; //销售品号

    //电信权益业务领取微信代金券配置
    protected $appId = '15028198';
    protected $appSecret = 'ZZDXPUBKEY';
//    protected $appId = '202010416';//测试
//    protected $appSecret = 'YSSTESTPUBKEY';//测试
    // protected $host = 'https://etctest.cyzl.com';//测试
//     protected $host = 'https://hsh-test.cyzl.com';//测试
    protected $host = 'https://hsh.cyzl.com';//生产

    public function _initialize()
    {
        parent::_initialize();
        $this->url = config('config.url');
        $this->key = config('config.key');
    }

    /*
     * 领取权益
    */
    public function receiveCoupon()
    {
        $time = time(); // 获取当前日期的时间戳
        $newtime = date('Y-m-d'); // 获取当天凌晨的格式化时间
        $ctime = strtotime(date($newtime.'08:00'.':00'));
        if ($time <= $ctime) {
            $this->error('8点以前不允许领取');
        }

        $BeginDate = date('Y-m-01');
        if ($newtime == $BeginDate) {
            $this->error('1号不允许领取');
        }

        $userid = $this->auth->id;
        $goods_id = $this->request->post('goods_id');
        $user_mobile = $this->request->post('user_mobile');
        $code_marking = $this->request->post('code_marking_yi'); //产品标识

        $goods_name = $this->request->post('goods_name', '');
        $goods_img = $this->request->post('goods_img', '');
        $goods_icon = $this->request->post('goods_icon', '');
        $brand_id = $this->request->post('brand_id', '');
        $brand_name = $this->request->post('brand_name', '');
        $category_id = $this->request->post('category_id', '');
        $category_name = $this->request->post('category_name', '');
        if (!$goods_id) {
            $this->error('无效的权益商品id！');
        }

        if (!$user_mobile) {
            $this->error('用户手机号不能为空！');
        }

        $userInfo = Db::name('user')->find($userid);
        if ($userInfo['is_quanyi'] !=1) {
            $this->error('您未订购业务');
        }

        if($user_mobile != '13303296677' && $user_mobile != '19930536605' && $user_mobile != '18131376849' && $user_mobile != '18131176617' && $user_mobile != '13313181805' && $user_mobile != '18931861094' && $user_mobile != '18903347106' && $user_mobile != '18903349505' && $user_mobile != '18903166118') {
            $beginThismonth=mktime(0,0,0,date('m'),1,date('Y'));
            $endThismonth=mktime(23,59,59,date('m'),date('t'),date('Y'));
            $data[] = ['create_time', 'between', [$beginThismonth,$endThismonth]];
            $data[] = ['user_id', '=', $userid];
            $info = Db::name('coupon_order')->where($data)->find();
            if ($info) {
                $this->error('本月已经领取过！');
            }
        }

        //过期时间
        $endtime = time() + 30*24*3600;
        $order_no = date('YmdHis', time()) . str_pad($userid, 5, 0, STR_PAD_LEFT) . rand(1000, 99999);//生成订单号

        if ($code_marking) { //获取微信代金券
            $info = $this->getPro($user_mobile, $code_marking, $order_no);
            if ($info['code']!=0) {
                $data = [ //请求失败添加日志
                    'user_id' => $userid,
                    'goods_id' => $goods_id,
                    'user_mobile' => $user_mobile,
                    'code_marking' => $code_marking,
                    'type' => 2,
                    'code' => $info['code'],
                    'msg' => $info['message'],
                    'create_time' => time()
                ];
                Db::name('coupon_log')->insertGetId($data);
                $this->error($info['message']);
            } else {
                $orderdata = [ //领取记录表
                    'order_no' => $order_no,
                    'user_id' => $userid,
                    'user_mobile' => $user_mobile,
                    'goods_id' => $goods_id,
                    'goods_name' => $goods_name,
                    'goods_img' => $goods_img,
                    'goods_icon' => $goods_icon,
                    'brand_id' => $brand_id,
                    'brand_name' => $brand_name,
                    'status' => 1,
                    'type' => 2,
                    'create_time' => time(),
                    'end_time' => $endtime
                ];
                Db::startTrans(); //开启事务
                try {
                    $ret = Db::name('coupon_order')->insertGetId($orderdata);
                    //取券码
                    if ($info['data']) {
                        foreach ($info['data'] as $key => $val) {
                            foreach ($val as $v) {
                                $data = [
                                    'order_id' => $ret,
                                    'order_no' => $order_no,
                                    'coupon_code_id' => $v,
                                    'coupon_code_category_id' => $category_id,
                                    'coupon_code_category_name' => $category_name,
                                    'coupon_code_name' => $goods_name,
                                    'car_number' => '',
                                    'car_mi' => '',
                                    'status' => 1,
                                    'type' => 2,
                                    // 'verification_code' => $userid.$goods_id.$key.date('His'),
                                    'create_time' => time(),
                                    'receive_time' => time()
                                ];

                                $jsondata = [
                                    'couponManageId' => $v,
                                    'mobilePhone' => $user_mobile,
                                    'name' => $goods_name,
                                    'orderId' => $order_no,
                                    'beginTime' => time(),
                                    'endTime' => $endtime,
                                    'type' => 1
                                ];
                                $posturl = json_decode($this->curl_post('http://shqyhadmin.jfxxl.net/index.php/api/Weichat/couponActive', $jsondata),true);
                                if ($posturl['code'] == 1) {
                                    $rets = true;
                                } else {
                                    $rets = false;
                                }
                            }

                            Db::name('coupon_order_details')->insert($data);
                        }
                    }
                    Db::commit();//提交事务
                    if ($rets) {
                        Smslib::send($user_mobile, null, 2, 'lingququanyi', $goods_name);//发送短信通知
                        $this->success('领取成功！', ['order_id' => $ret]);
                    } else {
                        $this->error('激活失败，请到‘生活权益惠’公众号激活使用！');
                    }

                } catch (Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error('领取失败！');
                }
            }

        } else { //本地权益
            $params = [
                'account' => '翼生活',
                'good_id' => $goods_id,
                'mobile' => $user_mobile,
                'end_time' => $endtime,
                'time' => time()
            ];
            $params['sign'] = $this->getSign($params, $this->key);
            $posturl = json_decode($this->curl_post($this->url . '/index.php/api/Coupon/goodsDetail', $params),true);
            if ($posturl['code'] == 0) {
                $this->error($posturl['msg'] . '---' . '效良-接口出错');
                // $this->error('效良-接口出错');
            }
            $orderdata = [ //领取记录表
                'order_no' => $order_no,
                'user_id' => $userid,
                'user_mobile' => $user_mobile,
                'goods_id' => $goods_id,
                'goods_name' => $posturl['data']['good']['name'],
                'goods_img' => $posturl['data']['good']['image'],
                'goods_icon' => $posturl['data']['good']['icon'],
                'brand_id' => $posturl['data']['brand']['id'],
                'brand_name' => $posturl['data']['brand']['username'],
                'status' => 1,
                'type' => 1,
                'create_time' => time(),
                'end_time' => $endtime
            ];
            Db::startTrans(); //开启事务
            try {
                $ret = Db::name('coupon_order')->insertGetId($orderdata);
                //取券码
                if ($posturl['data']['list']) {
                    foreach ($posturl['data']['list'] as $key => $val) {
                        $data = [
                            'order_id' => $ret,
                            'order_no' => $order_no,
                            'coupon_code_id' => $val['code_id'],
                            'coupon_code_category_id' => $val['category_id'],
                            'coupon_code_category_name' => $val['name'],
                            'coupon_code_name' => $posturl['data']['good']['name'],
                            'car_number' => $val['coupon_code'],
                            'car_mi' => $val['coupon_code_psd'],
                            'status' => 1,
                            'type' => 1,
                            // 'verification_code' => $userid.$goods_id.$key.date('His'),
                            'create_time' => time(),
                            'receive_time' => time()
                        ];
                        Db::name('coupon_order_details')->insert($data);
                    }
                }
                Db::commit();//提交事务
                $this->success('领取成功！', ['order_id' => $ret]);
            } catch (Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error('领取失败！');
            }
        }
    }

    /*
     * 领取详情
    */
    public function receiveDetails()
    {
        $userid = $this->auth->id;
        $order_id = $this->request->post('order_id');
        if (!$order_id) {
            $this->error('无效的订单id！');
        }
        $list['count'] = Db::name('coupon_order_details')->where(['order_id' => $order_id])->count();
        if ($list['count'] < 1) {
            $this->error('没有获取到相应数据！');
        }
        $list['data'] = Db::name('coupon_order_details')->where(['order_id' => $order_id])->select()->toArray();
        $this->success('获取成功！', $list);
    }

    /*
     * 领取记录
    */
    public function receiveCouponLog()
    {
        $userid = $this->auth->id;
        $page = $this->request->post('page', 1);
        $pagesize = 10;

        $where = [
            'user_id' => $userid,
            'status' => 1
        ];
        $list['count'] = Db::name('coupon_order')->where($where)->count();
        if ($list['count'] < 1) {
            $this->error('没有获取到相应数据！');
        }
        $list['goods'] = Db::name('coupon_order')->where($where)->page($page,$pagesize)->order('create_time desc')->select()->toArray();
        foreach ($list['goods'] as $key => $val) {
            $list['goods'][$key]['listcount'] = Db::name('coupon_order_details')->where(['order_id' => $val['id']])->count();
            // $list['goods'][$key]['list'] = Db::name('coupon_order_details')->where(['order_id' => $val['id']])->select()->toArray();
            $coupon_order_details = Db::name('coupon_order_details')->where(['order_id' => $val['id']])->select()->toArray();
            if ($val['type'] == 2 && $coupon_order_details) { //互联网权益兑换地址
                foreach ($coupon_order_details as $k => $v) {
                    $coupon_order_details[$k]['url'] = 'https://etc.cyzl.com/wetc/coupon_convert/index.html#/recharge?area=HebeiDianxin&couponManageId=' . $v['coupon_code_id'];
//                    $coupon_order_details[$k]['url'] = $this->host . '/wetc/coupon_convert/index.html#/recharge?area=HebeiDianxin&couponManageId=' . $v['coupon_code_id'];
                }
            }
            $list['goods'][$key]['list'] = $coupon_order_details;
        }
        $this->success('获取成功！', $list);
    }

    /**
     * 获取微信代金券领取记录
     */
    public function getWxCoupon()
    {
        $mobile = $this->request->post('mobile', '');
        $page = $this->request->post('page', 1);
        $pagesize = 50;
        if (!$mobile) {
            $this->error('手机号不能为空！');
        }
        $where = [
            'user_mobile' => $mobile,
            'status' => 1,
            'type' => 2,
        ];
        $info = Db::name('coupon_order')->where($where)->page($page,$pagesize)->order('create_time desc')->select()->toArray();
        foreach ($info as $key => $val) {
            $coupon_order_details = Db::name('coupon_order_details')->where(['order_id' => $val['id']])->select()->toArray();
            if ($val['type'] == 2 && $coupon_order_details) { //互联网权益兑换地址
                foreach ($coupon_order_details as $k => $v) {
                    $coupon_order_details[$k]['url'] = 'https://etc.cyzl.com/wetc/coupon_convert/index.html#/recharge?area=HebeiDianxin&couponManageId=' . $v['coupon_code_id'];
                }
            }
            $info[$key]['details'] = $coupon_order_details;
        }
        $this->success('获取成功！', $info);
    }

    /*
     * 核销权益
    */
    public function heXiao()
    {
        $params = $this->request->param();
        // $is_sign = $this->verifySign($params);
        // if (!$is_sign) {
        //     $this->error('签名错误');
        // }

        $info = Db::name('coupon_order_details')->where(['car_mi' => $params['car_mi']])->find();

        $ret = false;
        if ($info) {
            Db::startTrans();
            // foreach ($info as $key => $val) {
            try {
                Db::name('coupon_order_details')->where(['id' => $info['id']])->update(['status' => 2]);
                $data = Db::name('coupon_order_details')->where(['order_id' => $info['order_id'], 'status' => 1])->find();
                if (empty($data)) {
                    Db::name('coupon_order')->where(['id' => $info['order_id'], 'update_time' => time()])->update(['status' => 2]);
                }
                //提交事务
                Db::commit();
                $ret = true;
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }
            // }
        }
        if ($ret) {
            $this->success('修改成功');
        }else {
            $this->success('修改失败');
        }
    }

    /*
     * 检测用户是否订购电信权益
    */
    public function checkUserIsQuanYi()
    {
        $mobile = $this->request->post('mobile', '');
        if ($mobile == '13313181805' || $mobile == '13315681572' || $mobile == '13333304109') {
            Db::name('user')->where(['mobile' => $mobile])->update(['is_quanyi' => 1]);
            return json(['code' => 1, 'status' => 200, 'msg' => '用户已订购业务']);
        }
        if (!$mobile) $this->error('手机号不能为空！');
        $month = date('m');
        $param = [
            'timestamp' => (string)time(),
            'fromchannelId' => $this->fromchannelId,
            'signMerchantNo' => $this->signMerchantNo,
            'agreeId' => $this->agreeId,
            'signType' => $this->signType,
            'productNo' => $mobile
        ];
        //签名步骤一：按字典序排序参数
        ksort($param);
        $string = self::ToUrlParams($param);
        //签名步骤二：使用用户证书对第一步的字符串S1进行SHA256withRSA签名算法得到签名值S2
        $param['sign'] = $this->RsaEncrypt($string, $this->certpath);
        $url = $this->urls . '/electronic/quanyi/queryAssociateMember';
        $jsondata = json_encode($param);
        // $jsondata = '{"agreeId":"20200903030100040983812988993549","signMerchantNo":"3178035188579395","sign":"ZOyM+HocVBFzhgjxDWnsEYLIrBYnPnGVrgClcalnzmGjOMJg82ETAWQ+iRLuHvBqjnIQikToiYqVybPkq0k/nGVAdr5HrxpMdbn/bemsjo+6mZ839XvgMigzxdM6GnFt9rcL02uq3GMwgLRhad7UbeErYa75LqKlBuLdSZQFxJ0=","signType":"S001","fromchannelId":"HB13000002","productNo":"17317532008","timestamp":"1607308485"}';
        $result = $this->curl_json($url, $jsondata, $headerdata = [], false);
        if ($result['success'] == 1 && $result['result']) {
            if ($result['result']['vipOrderDetailsDtos']) {
                $res = false;
                foreach ($result['result']['vipOrderDetailsDtos'] as $key => $val) {
                    if ($val['orderStatus'] == 2) {
                        if ($val['crmSalesNo'] == $this->biaoshi || $val['crmSalesNo'] == $this->biaoshi1) {
                            $res = true;
                        }
                    }
                }
                if ($res) {
                    Db::name('user')->where(['mobile' => $mobile])->update(['is_quanyi' => 1]);
                    return json(['code' => 1, 'status' => 200, 'msg' => '用户已订购业务']);
                } else {
                    Db::name('user')->where(['mobile' => $mobile])->update(['is_quanyi' => 0]);
                    return json(['code' => 1, 'status' => 400, 'msg' => '用户未订购业务']);
                }
            } else {
                Db::name('user')->where(['mobile' => $mobile])->update(['is_quanyi' => 0]);
                return json(['code' => 1, 'status' => 400, 'msg' => '用户未订购业务']);
            }
        } else {
            $this->error($result['errorMsg']);
        }
    }

    /*
     * 生成 sha1WithRSA256 签名
     * @param data 加密的数据
     * @param pri_key 证书路径
    */
    public function RsaEncrypt($data,$pri_key = '')
    {
        openssl_pkcs12_read(file_get_contents($_SERVER['DOCUMENT_ROOT'].$pri_key), $certs, $this->priKeyPwd);
        // var_dump($res);die;
        // $signature = '';
        openssl_sign($data, $signMsg, $certs['pkey'], OPENSSL_ALGO_SHA256);
        return $signMsg ? base64_encode($signMsg) : "";
    }

    /*******************************优惠券领取接口strat*******************************************/

    /*
     * 优惠券领取
     * @param mobilePhone 手机号 string
     * @param proIdent 产品标识 string
    */
    public function getPro($mobilePhone, $proIdent, $order_no)
    {
        $params = [
            'mobilePhone' => $mobilePhone,
            'appId' => $this->appId,
            'proIdent' => (string)$proIdent,
            'apiVersion' => 'v1',
            'otherOrderId' => $order_no,
            'ip' => $this->request->ip(),
            'timestamp' => time() . '000'
        ];
        $params['sign'] = $this->craeteSign($params, $this->appSecret); //获取签名
        $params['accessToken'] = $this->getAccessToken(); //获取/刷新access_token
        $data = [
            'appId' => $this->appId,
            'proIdent' => (string)$proIdent,
            'mobilePhone' => $mobilePhone,
            'otherOrderId' => $order_no,
            'ip' => $this->request->ip(),
        ];
        $data = json_encode($data);
        $url = $this->host . '/api/v1/clien/openapi/getPro';
        $result = $this->curl_json($url, $data, $params, true);

        return $result;
    }

    /*
     * 获取产品标识
    */
    public function getProductIdents()
    {
        $params = [
            'appId' => $this->appId,
            'apiVersion' => 'v1',
            'timestamp' => time() . "000"
        ];
        $params['sign'] = $this->craeteSign($params, $this->appSecret); //获取签名
        $params['accessToken'] = $this->getAccessToken(); //获取/刷新access_token
        $data['appId'] = $this->appId;
        $data = json_encode($data);
        $url = $this->host . '/api/v1/clien/openapi/getProductIdents';
        $result = $this->curl_json($url, $data, $params, true);
        // print_r($result);die;
        if ($result['code'] == 0) {
            return $result['data']['proList'][0]['proIdent'];
        } else {
            return false;
        }
    }


    /*
     * 获取sign
     * @param params 参数 array
     * @param appSecret 秘钥 string
    */
    public function craeteSign($params = [], $appSecret = '')
    {
        //签名步骤一：排除为空参数
        foreach ($params as $key => $val) {
            if ($val == '' && !is_numeric($val)) {
                unset($params[$key]);
            }
        }
        //签名步骤二：按字典序排序参数
        ksort($params);
        //签名步骤三：拼接string，在string后加入KEY;
        $buff = '';
        foreach ($params as $k => $v) {
            if ($k != "sign" && $v != "" && !is_array($v)) {
                $buff .= $k . $v;
            }
        }
        $str = $buff . $appSecret;
        //签名步骤四：返回md5加密string
        return md5($str);
    }

    /*
     * 获取/刷新access_token
    */
    public function getAccessToken()
    {
//        $param = [
//            'appId' => $this->appId,
//            'appSecret' => $this->appSecret
//        ];
//
//        $jsondata = json_encode($param);
//        $url = $this->host . '/api/v1/interior/clien/openapi/getAccessToken';
        $url = 'http://shqyhadmin.jfxxl.net/index.php/api/weichat/getAccessToken';

        $result = $this->curlGet($url);
        return $result;
    }

    public function curlGet($url)
    {
        $header = array(
            'Accept: application/json',
        );
        $curl = curl_init();
        //设置抓取的url
        curl_setopt($curl, CURLOPT_URL, $url);
        //设置头文件的信息作为数据流输出
        curl_setopt($curl, CURLOPT_HEADER, 0);
        // 超时设置,以秒为单位
        curl_setopt($curl, CURLOPT_TIMEOUT, 1);

        // 超时设置，以毫秒为单位
        // curl_setopt($curl, CURLOPT_TIMEOUT_MS, 500);
        // 设置请求头
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        //设置获取的信息以文件流的形式返回，而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        //执行命令
        $data = curl_exec($curl);
        curl_close($curl);
        return $data;
    }

    /*
     * curl
     * @param $jsondata 业务参数 json
     * @param $headerdata 系统参数 array
    */
    public function curl_json($url, $jsondata, $headerdata = [], $is_json = false)
    {
        $ch = curl_init();
        if ($is_json) {
            $header = array ("Content-Type: application/json",
                'accessToken:' . $headerdata['accessToken'],
                'apiVersion:' . $headerdata['apiVersion'],
                'timestamp:' . $headerdata['timestamp'],
                'sign:' . $headerdata['sign'],
            );
        } else {
            $header =  array('Content-Type: application/json;charset=UTF-8');
        }
        curl_setopt_array($ch, array(
            CURLOPT_URL                =>  $url,
            CURLOPT_HTTPHEADER         =>  $header,
            CURLOPT_POST               =>  1,
            CURLOPT_SSL_VERIFYPEER     =>  FALSE,
            CURLOPT_SSL_VERIFYHOST     =>  FALSE,
            CURLOPT_RETURNTRANSFER     =>  1,
            CURLOPT_POSTFIELDS         =>  $jsondata
        ));

        $data = curl_exec($ch);
        curl_close($ch);

        return json_decode($data,true);
    }
}